import { getCampusSelector } from '@/api/campus/campus'
import { DICTIONARY_TYPES, getDictionaryData } from '@/utils/dictionaryConstants'
import request from '@/utils/request'
import CustomForm from './Form/index.vue'
import ImportForm from './ImportForm'
import RecordsForm from './Records/index.vue'
export default {
  name: 'insurance',
  components: { CustomForm, RecordsForm, ImportForm },
  data() {
    return {
      showAll: false,
      query: {
        campusId: undefined,
        campusStatus: ['preparation', 'normal', 'expires'],
        status: undefined,
        brand: 'bell',
        policyNumber: undefined,
        level: []
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      },
      formVisible: false,
      recordsVisible: false,
      importFormVisible: false,
      brandOptions: [],
      levelOptions: [],
      campusOptions: [],
      campusLoading: false,
      campusStatusOptions: [],
      companyOptions: [{ enCode: '总部区域', label: '总部区域' }, { enCode: '河北分公司', label: '河北分公司' }, { enCode: '山东分公司', label: '山东分公司' }, { enCode: '西安分公司', label: '西安分公司' }],
      //生效、失效、暂停、退费
      statusOptions: [
        {
          enCode: '1',
          fullName: '未参保'
        },
        {
          enCode: '2',
          fullName: '已参保'
        },
        {
          enCode: '3',
          fullName: '已过期'
        }
      ],
      policyNameOptions: [
        {
          enCode: '1',
          fullName: '三合一'
        },
        {
          enCode: '3',
          fullName: '公众责任险'
        },
        {
          enCode: '5',
          fullName: '公众责任险+雇主责任险'
        },
        {
          enCode: '6',
          fullName: '公众责任险+财产一切险'
        },
        {
          enCode: '7',
          fullName: '其他'
        }
      ],
      insuranceCompanyOptions: [
        {
          enCode: '1',
          fullName: '未办理'
        },
        {
          enCode: '2',
          fullName: '安亲保'
        },
        {
          enCode: '3',
          fullName: '放心保'
        },
        {
          enCode: '4',
          fullName: '平安保险'
        },
        {
          enCode: '5',
          fullName: '太平洋保险'
        },
        {
          enCode: '6',
          fullName: '中国人寿'
        },
        {
          enCode: '7',
          fullName: '阳光保险'
        },
        {
          enCode: '8',
          fullName: '其他'
        }
      ],
      columnList: [{ prop: 'campusId', label: '校区信息' }, { prop: 'policyName', label: '保险名称' }, { prop: 'policyNumber', label: '投保单号' }, { prop: 'effectiveDate', label: '生效日期' }, { prop: 'expirationDate', label: '到期日期' }, { prop: 'insuranceCompany', label: '投保公司' }, { prop: 'createTime', label: '创建时间' }, { prop: 'createUserName', label: '创建用户' }]
    }
  },
  computed: {},
  async created() {
    this.initData()
    this.loadCampusOptions()
    this.loadDictionaryData()
  },
  mounted() {
    this.$store.dispatch('base/getDictionaryData', { sort: 'CampusLevel' }).then(res => {
      this.levelOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'CampusStatus' }).then(res => {
      this.campusStatusOptions = res
    })
  },
  methods: {
    async loadCampusOptions() {
      try {
        this.campusLoading = true
        const params = {}
        if (this.query.brand) params.brand = this.query.brand
        if (this.query.company) params.company = this.query.company
        if (Array.isArray(this.query.campusStatus) && this.query.campusStatus.length) params.status = this.query.campusStatus.join()
        if (Array.isArray(this.query.level) && this.query.level.length) params.level = this.query.level.join()
        params.fields = 'id,fullName'
        const res = await getCampusSelector(params)
        this.campusOptions = Array.isArray(res.data) ? res.data : []
      } catch (error) {
        console.error('加载校区下拉选项失败:', error)
        this.$message.error('校区选项加载失败')
        this.campusOptions = []
      } finally {
        this.campusLoading = false
      }
    },
    async loadDictionaryData() {
      try {
        // 加载校区品牌数据字典
        this.brandOptions = await getDictionaryData(DICTIONARY_TYPES.BRAND)
      } catch (error) {
        console.error('加载数据字典失败:', error)
        this.$message.error('加载数据字典失败')
      }
    },
    ImportFormHandle() {
      this.importFormVisible = true
      this.$nextTick(() => {
        this.$refs.ImportForm.init()
      })
    },

    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      // 统一将 campusId 按照后端接口要求传递
      if (query.campusId === undefined || query.campusId === null || query.campusId === '') {
        delete query.campusId
      }
      request({
        url: `/api/campus/insurance`,
        method: 'GET',
        data: query
      }).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/system/CampusInsuranceRecords/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail)
      })
    },
    recordsHandle(id) {
      this.recordsVisible = true
      this.$nextTick(() => {
        this.$refs.RecordsForm.init(id)
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 50,
        sort: 'desc',
        sidx: 'createTime'
      }
      this.initData()
    },
    refresh(isrRefresh) {
      console.log(isrRefresh, 123)
      this.formVisible = false
      this.recordsVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 50,
        sort: 'desc',
        sidx: 'createTime'
      }
      this.initData()
    },
    goToStats() {
      this.$router.push('/campus/insurance/stats')
    }
  }
}
